package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    private final String PATTERN = "key_*";

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //开始分页
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        long total = page.getTotal();
        List<DishVO> result = page.getResult();
        log.info("菜品为：{}",result);
        return new PageResult(total,result);
    }

    /**
     * 菜品停售起售
     * @param status
     * @param id
     */
    @Override
    public void status(Integer status, Long id) {

        Dish dish = Dish.builder().status(status).id(id).build();

        //清理redis缓存
//        cleanCache(PATTERN);

        dishMapper.status(dish);
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Override
    public void delDishes(List<Long> ids) {

        for (Long id : ids) {
            //获取当前要删除的菜品信息
            Dish dish = dishMapper.getById(id);
//            DishDTO dishDTO = new DishDTO();
            //拷贝数据  dish-->dishDTO
//            BeanUtils.copyProperties(dish,dishDTO);
            Long dishId = dish.getId();
            log.info("当前要删除的菜品id为：{}",dishId);

            //判断当前菜品是否处于起售状态
            if(dish.getStatus().equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //判断当前是否被菜品关联
            SetmealDish setmealDish = setmealDishMapper.getByDishId(dishId);
            if(setmealDish != null){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

            //清理redis缓存
//            cleanCache(PATTERN);

            //删除菜品
            dishMapper.delDish(dish);
            //关联的口味数据也需要删除掉
            dishFlavorMapper.delFlavorsByDishId(dishId);
        }
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //查询菜品
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        //拷贝数据  dish-->dishDTO
        BeanUtils.copyProperties(dish,dishVO);
        //查询口味
        dishVO.setFlavors(dishFlavorMapper.getById(id));

        log.info("返回的菜品是，{}",dishVO.toString());

        return dishVO;
    }

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    public void save(DishDTO dishDTO) {

        //新增菜品
//        Dish dish = Dish.builder()
//                .id(dishDTO.getId())
//                .name(dishDTO.getName())
//                .categoryId(dishDTO.getCategoryId())
//                .price(dishDTO.getPrice())
//                .image(dishDTO.getImage())
//                .description(dishDTO.getDescription())
//                .build();
        Dish dish = new Dish();
        //拷贝数据  dishDTO-->dish
        BeanUtils.copyProperties(dishDTO,dish);

        //清理redis缓存
//        cleanCache(PATTERN);

        dishMapper.save(dish);

        //获取自增生成的id
        Long id = dish.getId();

        //新增口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors.size() > 0 && flavors != null){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            log.info("口味信息为：{}",flavors);
            dishFlavorMapper.save(flavors);
        }
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void updateDish(DishDTO dishDTO) {
        //修改菜品
        Dish dish = new Dish();
        //拷贝数据  dishDTO-->dish
        BeanUtils.copyProperties(dishDTO,dish);
        log.info("当前的菜品信息为：{}",dish);

        //清理redis缓存
//        cleanCache(PATTERN);

        dishMapper.updateDish(dish);

        //删除之前关联的口味信息
        dishFlavorMapper.delFlavorsByDishId(dish.getId());

        //修改菜品关联的口味（重新添加
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors.size() > 0 && flavors != null){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            log.info("口味信息为：{}",flavors);
            dishFlavorMapper.save(flavors);
        }
    }

    /**
     * 根据分类查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> getByCategoryId(Long categoryId) {
        log.info("id:{}",categoryId);
        return dishMapper.getByCategoryId(categoryId);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(Long categoryId) {

        List<DishVO> dishVOs = dishMapper.list(categoryId);

        for (DishVO dishVO : dishVOs) {
            Long dishId = dishVO.getId();
            dishVO.setFlavors(dishFlavorMapper.getById(dishId));
        }
        log.info("菜品为：{}",dishVOs);
        return dishVOs;
    }


}
